/**
 * 检查IMEI
 * @author dyh 2011-10-08
 */
package com.zjht.gmcc.servlet;

import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zjht.gmcc.bean.BaseServlet;
import com.zjht.gmcc.bean.action.IMEIUtil;
import com.zjht.gmcc.bean.util.MyFormat;
import com.zjht.gmcc.bean.util.MyJDBC;

public class IMEICheck extends BaseServlet {

	private static final long serialVersionUID = 494933415316360211L;

	public boolean process(HttpServletRequest request, HttpServletResponse response, HttpSession session, PrintWriter out, MyJDBC myJDBC, String menu)
			throws Exception {
		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuilder sb = new StringBuilder("<state>");
		String IMEIs = request.getParameter("IMEIs");
		int productid = MyFormat.formatInt(request.getParameter("productid"));
		String orgcode = MyFormat.formatStr(request.getParameter("orgcode"));
		String provider = MyFormat.formatStr(request.getParameter("provider"));
		String goodflag = MyFormat.formatStr(request.getParameter("goodflag"), "1");// 是否良品
		String validflag = MyFormat.formatStr(request.getParameter("validflag"), IMEIUtil.VALIDFLAG_OK);// 0:在途,1:在库,2-锁定

		if (!MyFormat.isStrNull(IMEIs) && !MyFormat.isStrNull(orgcode) && productid > 0) {
			boolean hasProvider = !MyFormat.isStrNull(provider);
			String IMEI = "";
			PreparedStatement ps;
			ResultSet rs;
			StringBuilder sql = new StringBuilder();
			sql
					.append("SELECT 1 FROM DUAL WHERE exists(SELECT 1 FROM IMEI WHERE IMEI=? AND OrgaCode=? AND ProductID=? AND SendFlag=? AND goodFlag=?");
			if (!MyFormat.isStrNull(provider)) {
				sql.append(" AND provorgacode=?");
			}
			sql.append(")");
			ps = myJDBC.prepareStatement(sql);
			ps.setString(2, orgcode);
			ps.setInt(3, productid);
			ps.setString(4, validflag);
			ps.setString(5, goodflag);
			if (hasProvider) {
				ps.setString(6, provider);
			}

			StringTokenizer st = new StringTokenizer(IMEIs, ",");
			while (st.hasMoreTokens()) {
				if (st.hasMoreTokens()) {
					IMEI = st.nextToken();
					ps.setString(1, IMEI);
					rs = ps.executeQuery();
					if (rs.next()) {
						sb.append("<value>" + IMEI + "</value>");
					}
					rs.close();
					rs = null;
				}
			}
			ps.close();
			ps = null;
			st = null;
			sql = null;
		}
		sb.append("</state>");
		out.write(sb.toString());
		sb = null;
		return true;
	}
}
